package com.windoent.yugioh.ui.activity.saishi;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.SaiShiSearchPageAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.SaiShiListDataBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.help.AndroidScheduler;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.JumpHelper;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.SearchView;
import com.windoent.yugioh.widget.dialog.SureNotDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/7/16 13:37
 * desc   :赛事搜索
 */
public class SaiShiSearchActivity extends BaseActivity {
    private SearchView mSearch;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private View mView;
    private LinearLayout mLlBack;

    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private SaiShiSearchPageAdapter adapter;

    @Override
    public int getLayout() {
        return R.layout.activity_saishi_search;
    }

    @Override
    public void initView() {
        super.initView();
        mView = (View) findViewById(R.id.view);
        immersiveStatusBar(mView);
        mLlBack = (LinearLayout) findViewById(R.id.ll_back);
        mSearch = (SearchView) findViewById(R.id.search);
        mSmartLayout = (SmartRefreshLayout) findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    }

    @Override
    public void initData() {
        super.initData();
        initAdapter();
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new SaiShiSearchPageAdapter();
        adapter.setAnimationEnable(false);
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerView, false));
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                List<SaiShiListDataBean.DataBean.MatchsBean> data = adapter.getData();
                if (data != null) {
                    SaiShiListDataBean.DataBean.MatchsBean matchsBean = data.get(position);
                    if (matchsBean != null) {
                        int id = matchsBean.getId();
                        int rule = matchsBean.getRule();
                        JumpHelper.startGameTab(mContext, id + "", rule + "");
                    }
                }
            }
        });
        adapter.addChildClickViewIds(R.id.ll_yuyue);
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                List<SaiShiListDataBean.DataBean.MatchsBean> data = adapter.getData();
                if (data != null) {
                    SaiShiListDataBean.DataBean.MatchsBean matchsBean = data.get(position);
                    if (matchsBean != null) {
                        int viewId = view.getId();
                        int id = matchsBean.getId();
                        int rule = matchsBean.getRule();
                        if (viewId == R.id.ll_yuyue && matchsBean.getBottom() != null && matchsBean.getBottom().getType() == 3) {
                            //点击预约
                            showSureYuYueDialog(id);
                        } else {
                            JumpHelper.startGameTab(mContext, id + "", rule + "");
                        }
                    }
                }
            }
        });
    }

    //预约比赛
    private void showSureYuYueDialog(int id) {
        SureNotDialog dialog = new SureNotDialog(mContext);
        dialog.setYesStr(getString(R.string.string_yuyue_warning));
        dialog.setNoStr(getString(R.string.dl_cancel));
        dialog.setTvContent(getString(R.string.string_if_yuyue_warn));
        dialog.setYesOnclickListener(new SureNotDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {

            }
        });
        dialog.show();
    }

    private void initRefreshData(String type) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(type);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore(type);
            }
        });
    }

    private void loadMore(String type) {
        mCount = mCount + 1;
        getSaiShiList(type, mCount + "", limit, false);
    }

    private void fresh(String type) {
        mCount = 1;
        getSaiShiList(type, mCount + "", limit, true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        if (adapter != null) {
            adapter.resetNotifyTime();
        }
        if (mTimeCountDisposable != null) {
            mTimeCountDisposable.dispose();
        }
    }

    //赛事搜索
    private void getSaiShiList(String type, String limit, String code, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getSearchSaiShiList(getUserToken(), type, limit, code, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            SaiShiListDataBean json = gson.fromJson(response, SaiShiListDataBean.class);
                            SaiShiListDataBean.DataBean data = json.getData();
                            if (data != null) {
                                List<SaiShiListDataBean.DataBean.MatchsBean> matchs = data.getMatchs();
                                if (matchs != null && matchs.size() > 0) {
                                    adapter.resetNotifyTime();
                                    if (fresh) {
                                        adapter.setNewInstance(matchs);
                                        mSmartLayout.finishRefresh(true);
                                    } else {
                                        adapter.addData(matchs);
                                        adapter.notifyDataSetChanged();
                                        mSmartLayout.finishLoadMore(true);
                                    }
                                    //数据错乱
                                    mRecyclerView.setItemViewCacheSize(adapter.getData().size());
                                    TimeCount(Integer.MAX_VALUE);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        ToastUtils.showText(getString(R.string.string_no_data));
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Override
    public void initListener() {
        super.initListener();
        mLlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mSearch.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    //此处做逻辑处理
                    String text = mSearch.getEditStr();
                    initRefreshData(text);
                    fresh(text);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛事搜索界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛事搜索界面");
    }

    private Disposable mTimeCountDisposable;

    /**
     * 倒计时
     *
     * @param count
     */
    public void TimeCount(int count) {
        if (mTimeCountDisposable != null) {
            //取消上一次的订阅
            mTimeCountDisposable.dispose();
        }
        //0-count依次输出，延时0s执行，每1s发射一次。
        mTimeCountDisposable = Flowable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS)
                .onBackpressureDrop()//过滤（抛弃）或者onBackpressurebuffer 缓存
                .observeOn(AndroidScheduler.mainThread())
                .doOnNext(aLong -> {
                    assert adapter != null;
                    adapter.notifyTime();
                })
                .doOnComplete(() -> {
                    if (mTimeCountDisposable != null)
                        mTimeCountDisposable.dispose();
                })
                .subscribe();
    }
}
